<template>
  <!-- 字体图标版，比较好用，能使用建议使用，但是如果是字体图标没有的表情，很难加 -->
  <div class="home">
    <div class="editor" contenteditable="true" ref="editor" placeholder="默认文字"></div>
    <VEmojiPicker :pack="pack" @select="selectEmoji" />
  </div>
</template>

<script>
import VEmojiPicker from "v-emoji-picker";
import packData from "v-emoji-picker/data/emojis.json";
export default {
  name: "home",
  components: {
    VEmojiPicker
  },
  data() {
    return {
      pack: packData.data,
      emoji: null
    };
  },
  created() {
    console.log(this.pack);
  },
  methods: {
    // getSelection、createRange兼容
    isSupportRange() {
      return (
        typeof document.createRange === "function" ||
        typeof window.getSelection === "function"
      );
    },
    // 获取光标位置
    getCurrentRange() {
      let range = null;
      let selection = null;
      if (this.isSupportRange()) {
        selection = document.getSelection();
        if (selection.getRangeAt && selection.rangeCount) {
          range = document.getSelection().getRangeAt(0);
        }
      } else {
        range = document.selection.createRange();
      }
      return range;
    },
    // 插入内容
    insertHtmlAfterRange(html) {
      let selection = null;
      let range = null;
      if (this.isSupportRange()) {
        // IE > 9 and 其它浏览器
        selection = document.getSelection();
        if (selection.getRangeAt && selection.rangeCount) {
          let fragment, node, lastNode;
          range = selection.getRangeAt(0);
          range.deleteContents();
          let el = document.createElement("span");
          el.innerHTML = html;
          // 创建空文档对象,IE > 8支持documentFragment
          fragment = document.createDocumentFragment();

          while ((node = el.firstChild)) {
            lastNode = fragment.appendChild(node);
          }
          range.insertNode(fragment);

          if (lastNode) {
            range = range.cloneRange();
            range.setStartAfter(lastNode);
            range.collapse(true);
            selection.removeAllRanges();
            selection.addRange(range);
          }
        }
      } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
      }
    },
    selectEmoji(emoji) {
      this.$refs.editor.focus();
      this.insertHtmlAfterRange(emoji.emoji);
    }
  }
};
</script>

<style lang="scss" scoped>
.home {
  // placeholder 样式
  [contenteditable="true"]:empty::before {
    content: attr(placeholder);
    color: #ccc;
    caret-color: #ccc;
  }
  .editor {
    width: 90%;
    margin: auto;
    padding: 10px 0;
    text-align: left;
    caret-color: #333;
    color: #333;
  }
}
</style>
